<?php


namespace app\controller\admin\school;


use app\controller\admin\BaseAdminController;
use app\model\school\SchoolCourseModel;
use app\model\school\SchoolModel;

class SchoolCourseController extends BaseAdminController
{

    function setModel()
    {
        return new SchoolCourseModel();
    }

    function setWithModel()
    {
        return ['school'];
    }

    function setSearch()
    {
        $where = [];
        return [
            'like' => ['name', 'school.name' => 'school_name'],
            'custom' => $where
        ];
    }

    function setSort()
    {
        // TODO: Implement setSort() method.
    }

    public function save()
    {
        try {
            $data = $this->request->only(['id', 'school_id', 'type', 'name', 'img', 'old_price', 'price', 'detail']);


            $id = $data['id'] ?? 0;
            if (!$id) {
                $dataAll = [];
                foreach ($data['school_id'] as $k => $datum) {
                    $dataAll[$k] = [
                        'school_id' => $datum,
                        'type' => $data['type'],
                        'name' => $data['name'],
                        'img' => $data['img'],
                        'old_price' => $data['old_price'],
                        'price' => $data['price'],
                        'detail' => $data['detail'],
                    ];
                }
                $model = $this->setModel();
                $model->saveAll($dataAll);
            } else {
                $model = $this->setModel()->where('id', $id)->find();
                $model->save($data);
            }
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }
}